//
//  TYZTool.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/10.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "TYZTool.h"

@implementation TYZTool

/**
 生成当前的GUID

 @return GUID
 */
+ (NSString *)GUID {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    NSString *str = (__bridge NSString *)string;
    CFRelease(string);
    return str;
}

/**
 根据日期得到当前星期几

 @param dateString 年月日字符串，字符格式为yyyy-MM-dd
 @return 星期几（0是星期日）
 */
+ (NSInteger)weekFromDateString:(NSString *)dateString {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    [fmt setTimeZone:GTMzone];
    [fmt setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [fmt dateFromString:dateString];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:date];
    return weekdayComponents.weekday - 1;
}

/**
 判断当月有多少天

 @param month 月份
 @param year 年份
 @return 多少天
 */
+ (NSInteger)daysInMonth:(NSInteger)month year:(NSInteger)year {
    if (
        month == 1 ||
        month == 3 ||
        month == 5 ||
        month == 7 ||
        month == 8 ||
        month == 10 ||
        month == 12
        ) {
        return 31;
    }
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        return 30;
    }
    if (month == 2 && (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) {
        return 29;
    } else {
        return 28;
    }
}

/**
 获取当天所在周的第一天和最后一天

 @param dateString 当天的日期年月日字符串，字符格式为yyyy-MM-dd
 @return 第一天和最后一天的数组
 */
+ (NSArray<NSString *> *)weekTypeDayArrayWithDateString:(NSString *)dateString {
    if (dateString.length < 10) return @[dateString, dateString];
    NSInteger year = [[dateString substringWithRange:NSMakeRange(0, 4)] integerValue];
    NSInteger month = [[dateString substringWithRange:NSMakeRange(5, 2)] integerValue];
    NSInteger day = [[dateString substringWithRange:NSMakeRange(8, 2)] integerValue];
    // 记录结尾的年份和月份
    NSInteger endMonth = month;
    NSInteger endYear = year;
    // 当天是星期几
    NSInteger weekDay = [self weekFromDateString:dateString];
    // 本周第一天是哪一天
    NSInteger firstDay = day - weekDay;
    // 特殊情况的判断
    if (firstDay < 0) {
        // 前月多少天
        month -= 1;
        if (month < 1) {
            month = 12;
            year -= 1;
        }
        NSInteger prefixMonthDays = [self daysInMonth:month year:year];
        firstDay = prefixMonthDays + firstDay;
    }
    NSString *startDay = [NSString stringWithFormat:@"%ld-%ld-%02ld", (long)year, (long)month, (long)firstDay];
    // 本月多少天
    NSInteger monthDays = [self daysInMonth:month year:year];
    // 本周最后一天是哪一天
    NSInteger lastDay = day + (6 - weekDay);
    // 特殊情况的判断
    if (lastDay > monthDays) {
        lastDay -= monthDays;
        endMonth += 1;
        if (endMonth > 12) {
            endMonth = 1;
            endYear += 1;
        }
    }
    NSString *endDay = [NSString stringWithFormat:@"%ld-%ld-%02ld", (long)endYear, (long)endMonth, (long)lastDay];
    return @[startDay, endDay];
}

/**
 获取当天所在月的第一天和最后一天
 
 @param dateString 传入的日期格式为（yyyy-mm-dd）
 @return 第一天和最后一天的数组
 */
+ (NSArray<NSString *> *)monthTypeDayArrayWithDateString:(NSString *)dateString {
    if (dateString.length < 7) return @[dateString, dateString];
    NSInteger year = [[dateString substringWithRange:NSMakeRange(0, 4)] integerValue];
    NSInteger month = [[dateString substringWithRange:NSMakeRange(5, 2)] integerValue];
        // 本月多少天
    NSInteger monthDays = [self daysInMonth:month year:year];
    NSString *startDay = [NSString stringWithFormat:@"%ld-%ld-01", (long)year, (long)month];
    NSString *endDay = [NSString stringWithFormat:@"%ld-%ld-%ld", (long)year, (long)month, (long)monthDays];
    return @[startDay, endDay];
}

/**
  获取当地当前时间
 
  @return 时间字符串
*/
+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // yyyy-MM-dd 可自定义，也可以换成 yyyy-MM-dd HH:MM:SS
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
    
}

/**
  将字符串转成NSDate类型
 
  @param dateString 时间类型的字符串 例如：2018-07-12
  @return date
*/
+ (NSDate *)dateFromString:(NSString *)dateString {
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *inputDate = [inputFormatter dateFromString:dateString];
    //inputDate或出现相差八小时问题，下面是解决相差八小时
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: inputDate];
    NSDate *localeDate = [inputDate dateByAddingTimeInterval: interval];
    return localeDate;
    
}

/**
  传入今天的时间，返回第二天的时间（yyyy-MM-dd）
 
  @param aDate 当前的时间NSDate类型，上面的方法可获取当前时间的NSDate类型
  @return 第二天时间
*/
+ (NSString *)getTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday |NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
    
}

/**
 获取几天之后的时间

 @param someDay 几天？
 @param format 时间格式
 @return 几天之后的时间
 */
+ (NSString *)getAfterSomeDay:(NSInteger)someDay format:(NSString *)format {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday |NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    [components setDay:([components day]+someDay)];
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:format];
    return [dateday stringFromDate:beginningOfWeek];
    
}

/**
  判断是否为今天
 
  @param todayTime 时间（NSDate）
  @return YES，是 NO ～
*/
+ (BOOL)isTodayWithTime:(NSDate*)todayTime {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:[NSDate date]];
    NSDate *today = [cal dateFromComponents:components];
    components = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:todayTime];
    NSDate *otherDate = [cal dateFromComponents:components];
    if([today isEqualToDate:otherDate]) {
        return YES;
    }
    return NO;
}

/**
  获取当前时间戳
  *1000 是精确到毫秒，不乘就是精确到秒
 
  @return 返回时间戳
*/
+ (NSString *)currentTimeStr {
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

/**
  时间戳转时间,时间戳为13位是精确到毫秒的，10位精确到秒
  传入的时间戳str如果是精确到毫秒的记得要/1000
 
  @param timeStr 时间戳
  @return 返回时间
*/
+ (NSString *)getDateStringWithTimeStr:(NSString *)timeStr {
    NSTimeInterval time=[timeStr doubleValue]/1000;//传入的时间戳str如果是精确到毫秒的记得要/1000
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SS"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}

/**
  字符串转时间戳 如：2017-4-10 17:15:10

  @param time 时间
  @return 时间戳
*/
+ (NSString *)getTimeStrWithString:(NSString *)time {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:time];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}

/**
  获取当前是星期几
 
  @return 1、2、3、4、5、6、7(星期六是 7 ，星期日 1)
*/
+ (NSInteger)getNowWeekday {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDate *now = [NSDate date];
    // 在真机上需要设置区域，才能正确获取本地日期，中国区代码：zh_CN
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    NSDateComponents *comps = [calendar components:unitFlags fromDate:now];
    return [comps weekday];
}

/**
  获取当前是几月几日

  @return 07月07日
*/
+ (NSString *)getTodayStr {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:[NSDate date]];
    NSDate *today = [cal dateFromComponents:components];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM月dd日";
    return [formatter stringFromDate:today];
    
}

/**
  计算两个时间的差值

  @param starTime 开始时间
  @param endTime 结束时间
  @return 时间差 (单位 ：秒)
*/
+ (NSTimeInterval)pleaseInsertStarTime:(NSString *)starTime andInsertEndTime:(NSString *)endTime {
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd"];//根据自己的需求定义格式
    NSDate* startDate = [formater dateFromString:starTime];
    NSDate* endDate = [formater dateFromString:endTime];
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    return time;
}
@end
